package charlie.util;
/**
 * --- Java Binary Converter Class ---
 *
 * Converts any signed two's complement integer (byte, short, int, long)
 * into a binary representation of the given value as a String of ones and zeros.
 *
 * @author Neil Smith
 * @copyright 2007 Neil Smith <jsmin@nsmith.me.uk>
 * @link http://www.nsmith.me.uk/java-binary-converter/
 * @license http://www.apache.org/licenses/LICENSE-2.0.txt Apache License, Version 2.0
 * @version 1.0.0 (2008-06-25)
 *
 */


public class Binary {

	// Base to convert to. 2 for binary.
	final static byte base = 2;

	//--------------------------------------------

	// 8-bit
	public static String decbin( byte n ){
		//---
		return decbin(n, (byte)8);
		//---
	}

	// 16-bit
	public static String decbin( short n ){
		//---
		return decbin(n, (byte)16);
		//---
	}

	// 32-bit
	public static String decbin( int n ){
		//---
		return decbin(n, (byte)32);
		//---
	}

	// 64-bit
	public static String decbin( long n ){
		//---
		return decbin(n, (byte)64);
		//---
	}

	//--------------------------------------------

	private static String decbin( long n, byte padding ){

		//char padd = '0';	// Left padding used for a +ve number.

		String s = "";		// Will hold the binary string.

		//---

		//Records whether the passed number is negative...
		boolean negative = (n < 0);

		//If the value is negative, convert to be represented in two's complement binary.
		if ( negative ){
            //---
            n = Math.abs(n);	// Get the absolute (+ve) value of the number.
        	n = ~n;				//Invert all the bits within the value.
        	n = n << 1;			//Shift all the bits one place to the left.
        	//---
		}

		//---

		//Build the string...
		while( n != 0 ){

			//Add the "bit" to the START of the string...
			s = Math.abs(n%base) + s;

			n = n/base;

		}

		//---

		//If the value is negative, append '1' to the start of the string to denote it's a negative.
/*		if ( negative ){
			s = "1" + s;
			//padd = '1';	// Left padding used for a -ve number.
		} else {
			s = "0" + s;
			//padd = '1';	// Left padding used for a -ve number.
		}
*/
		//---

		//Padding the string with zeros/ones to the left...
		//while (s.length() < padding){
		//	s = padd + s;
		//}

		//---

		return s;

	}

}